package net.weitalk.newfeatures;

import java.util.Calendar;

/**
 * 该怎么用代码计算一个月有多少天？
 * “一三五七八十腊，三十一天永不差，四六九冬三十整，平年二月二十八，闰年二月把一加”。
 * switch expression @since JDK14.
 */
public class DaysInMonthSwitchExpression {
    private static boolean isLeapYear(int year) {
        return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
    }

    public static void main(String[] args) {
        Calendar today = Calendar.getInstance();
        int month = today.get(Calendar.MONTH);
        int year = today.get(Calendar.YEAR);
        int daysInMonth = switch (month) {
            case Calendar.JANUARY,
                    Calendar.MARCH,
                    Calendar.MAY,
                    Calendar.JULY,
                    Calendar.AUGUST,
                    Calendar.OCTOBER,
                    Calendar.DECEMBER -> 31;
            case Calendar.APRIL,
                    Calendar.JUNE,
                    Calendar.SEPTEMBER,
                    Calendar.NOVEMBER -> 30;
            case Calendar.FEBRUARY -> {
                if (isLeapYear(year)) {
                    yield 29;
                } else {
                    yield 28;
                }
            }
            //如果没有最后的 default 情景分支，编译器就会报错。这是一个影响深远的改进，
            //它会使得 switch 表达式的代码更加健壮，大幅度降低维护成本，如果未来需要增加一个情景分支的话，就更是如此了。
            default -> throw new RuntimeException("Calendar not work!");
        };
        System.out.println("There are " + daysInMonth + " days in this month.");
    }
}
